package com.itheima.controller;


import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.itheima.common.pojo.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

/**
 * @author 86188
 */

@RestController
@RequestMapping("/common")
@Slf4j
public class CommonController {

    @Value("${oss.endpoint}")
    private String endpoint;
    @Value("${oss.accesskey}")
    private String accessKeyId;
    @Value("${oss.secret}")
    private String accessKetSecret;
    @Value("${oss.bucketName}")
    private String bucketName;
    @Value("${oss.url}")
    private String ossUrl;

    @PostMapping("/upload")
    public Result upload(MultipartFile file) {
        String fileName = file.getOriginalFilename();

        // 创建OSSClient实例。
        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKetSecret);
        try {
            ossClient.putObject(bucketName, fileName, file.getInputStream());
        } catch (Exception oe) {
            log.error("上传文件异常");
        } finally {
            if (ossClient != null) {
                ossClient.shutdown();
            }
        }
        String fileUrl = ossUrl + fileName;
        return Result.success("成功", fileUrl);

    }
}






